# coding: utf-8
from google.appengine.ext import ndb
from google.appengine.api import users


class Book(ndb.Model):
	'''A book is the root container for all other entities in GnuCash.'''
	name = ndb.StringProperty(required=True)
	@classmethod
	def getByUrlSafeKey(cls, urlsafeKey):
		return ndb.Key(urlsafe=urlsafeKey).get()
	@classmethod
	def listByCurrentUser(cls):
		userID = users.get_current_user().user_id()
		userKey = ndb.Key('User', userID)
		return cls.query(ancestor=userKey).order(cls.name)
	@classmethod
	def listAll(cls):
		return cls.query()


AccountCategories = {0:'asset', 1:'liability', 2:'income', 3:'expense'}


class Account(ndb.Model):
	'''Accounts are the containing entity for transactions'''
	name = ndb.StringProperty(required=True)
	description = ndb.StringProperty(required=True)
	category = ndb.IntegerProperty(choices=AccountCategories.keys(), required=True)
	@classmethod
	def getByUrlSafeKey(cls, urlsafeKey):
		return ndb.Key(urlsafe=urlsafeKey).get()
	@classmethod
	def listByBook(cls, book):
		return cls.query(ancestor=book.key).order(cls.category, cls.name)
	def getCategoryName(self):
		return AccountCategories[self.category]
Account.reflex = ndb.KeyProperty(kind=Account)

class Split(ndb.Model):
	'''Splits tie an amount of a commodity to a single account in a transaction.'''
	account = ndb.KeyProperty(kind=Account, required=True)
	value = ndb.IntegerProperty(required=True)
	quantity = ndb.IntegerProperty()
	memo = ndb.StringProperty()


class Transaction(ndb.Model):
	'''Transactions are transfers of commodities between accounts; if the accounts are for different commodities, then a price is created as the ratio of the quantities in each. Transactions must contain at least two splits, and the credits and debits in the splits must sum to the same amount -- they must balance.'''
	date = ndb.DateProperty(required=True)
	description = ndb.StringProperty(required=True)
	splits = ndb.StructuredProperty(Split, repeated=True)

